<%@ page language="java"  pageEncoding="UTF-8" 
  import="
    java.io.*,
    com.alibaba.fastjson.*,
    com.github.cuter44.wxmp.*,
    com.github.cuter44.wxmp.reqs.*,
    com.github.cuter44.wxmp.resps.*,
    com.github.cuter44.nyafx.crypto.Base64
  "
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>

  <body>
    <h1>上传临时素材-图像</h1>
    <span color="red">不要在生产环境保留此页面, 会暴露 access_token</span>

    <p />

    <form id="form" enctype="application/x-www-form-urlencoded" method="post">
      图像...的 data-url:
      <br />
      <span style="color:gray; font-size:small;">因为不想引入不必要的依赖性<span style="background-color:gray">以及作者懒癌发作</span>所以要用data-url</span>
      <br />
      <span style="color:gray; font-size:small;">转换 data-url 的工具可以在<a href="http://www.atool.org/img2base64.php">这里↗</a>找到</span>
      <br />
      <textarea style="height:480px; width:640px;" name="file">
      </textarea>
      <br />
      <input type="submit" />
    </form>

    <p />

    <% 
      String file = request.getParameter("file");
      if (file != null)
      {
        String[] s0 = file.split(";");
        String contentType = s0[0].replaceFirst("data\\:", "");
        String strContent = s0[1].replaceFirst("base64\\,", "");
        System.out.println(strContent.substring(0, 100));

        byte[] binContent = Base64.decode(strContent);
        ByteArrayInputStream streamContent = new ByteArrayInputStream(binContent);

        WxmpFactory factory = WxmpFactory.getDefaultInstance();

        MediaUploadImage wxreq1 = (MediaUploadImage)factory.instantiate(MediaUploadImage.class);
        wxreq1.setAccessToken(factory.getTokenKeeper().getAccessToken());
        wxreq1.setFilename("file.jpg");
        wxreq1.setMedia(streamContent);
        wxreq1.setContentType(contentType);

        MediaUploadResponse wxresp1 = wxreq1.build().execute();
        JSONObject prop1 = wxresp1.getJson();
        System.out.println(prop1);

        out.println(prop1);
        out.println("<br />");

        String accessToken = factory.getTokenKeeper().getAccessToken();
        String mediaId = wxresp1.getMediaId();

    %>
      <img src="https://api.weixin.qq.com/cgi-bin/media/get?access_token=<%=accessToken%>&media_id=<%=mediaId%>" />
    <%
      }
    %>

  </body>
</html>
